# 作者: YYJ
# 2025年07月08日13时23分06秒
# 2486249622@qq.com


import socket
import sys
import select



class ChatServer:
    def __init__(self, ip, port):
        self.ip =  ip
        self.port = port
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)   # 设置端口复用
        self.server.bind((self.ip, self.port))
        self.server.listen(10)
        self.epoll = select.epoll()

    def chat(self):
        conn, addr = self.server.accept()
        print("Connected by", addr)
        self.epoll.register(conn.fileno(), select.EPOLLIN)  # 监控连接（读事件）
        self.epoll.register(sys.stdin.fileno(), select.EPOLLIN)    # 监控标准输入
        while True:
            events = self.epoll.poll(-1)
            for fd, event in events:
                if fd == sys.stdin.fileno():       # 如果标准输入触发，则从标准输入中获取数据，并写入连接
                    data = input()
                    conn.send(data.encode('utf-8'))
                elif fd == conn.fileno():       # 如果连接触发，则从连接中获取数据，并打印到标准输出
                    if event & select.EPOLLIN:
                        data = conn.recv(1024).decode('utf-8')
                        if data:
                            print("Client:", data)
                        else:
                            print("Connection closed")
                            break

if __name__ == '__main__':
    server = ChatServer('127.0.0.1', 8000)
    server.chat()